package com.fulihui.information.service;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;

import java.security.MessageDigest;

import static org.junit.Assert.assertEquals;

/**
 * @author Willard.Hu on 2017/1/17 0017.
 */
public class SelfCipher {
    int num = 27; // 随便定义一个整数

    @Test
    public void test_func() throws Exception {
        // org.apache.commons.lang3.RandomStringUtils
        String key = RandomStringUtils.randomAlphanumeric(128);
        System.out.println("src ===> " + key);
        String encrypted = encrypt(key);
        System.out.println("encrypted ===> " + encrypted);
        // org.junit.Assert.assertEquals
        assertEquals(key, decrypt(encrypted));

        // 签名算法
        // java.security.MessageDigest
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        // org.apache.commons.codec.binary.Hex
        String sign = Hex.encodeHexString(md.digest(key.getBytes("UTF-8")));
        System.out.println("sign ===> " + sign);
    }

    String encrypt(String src) {
        if (src == null || src.isEmpty()) {
            return null;
        }
        byte[] buff = src.getBytes();
        byte[] random = RandomStringUtils.randomAlphanumeric(buff.length).getBytes();
        int newSize = buff.length * 2;
        byte[] newBuff = new byte[newSize];
        for (int i = 0, j = 0; i < newSize; i += 2, j++) {
            newBuff[i] = (byte) (buff[j] ^ num);
            newBuff[i + 1] = (byte) (random[j] ^ num);
        }
        // org.apache.commons.codec.binary.Base64
        return Base64.encodeBase64String(newBuff);
    }

    String decrypt(String encrypted) {
        if (encrypted == null || encrypted.isEmpty()) {
            return null;
        }
        // org.apache.commons.codec.binary.Base64
        byte[] buff = Base64.decodeBase64(encrypted);
        byte[] newBuff = new byte[buff.length / 2];
        for (int i = 0, j = 0; i < buff.length; i += 2, j++) {
            newBuff[j] = (byte) (buff[i] ^ num);
        }
        return new String(newBuff);
    }
}
